package main

import (
	"fmt"
	"html/template"
	"io"
	"net/http"
	"strconv"

	"github.com/facebookgo/grace/gracehttp"
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
	"m-project-admin/app/before"
	_ "m-project-admin/app/model"
	"m-project-admin/app/router"
	"m-project-admin/app/utils"
)

type Template struct {
	templates *template.Template
}

func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
	return t.templates.ExecuteTemplate(w, name, data)
}

var port = 15001

func init() {
	tmpPort := utils.GetSectionValue("server", "port", "")
	iniPort, err := strconv.Atoi(tmpPort)
	if err == nil {
		port = iniPort
	}
}

// 错误页面导向
func customHTTPErrorHandler(err error, c echo.Context) {
	code := http.StatusInternalServerError
	if he, ok := err.(*echo.HTTPError); ok {
		code = he.Code
	}
	errorPage := fmt.Sprintf("%d.html", code)
	if err := c.File(errorPage); err != nil {
		c.Logger().Error(err)
	}
	c.Logger().Error(err)
}

func main() {
	e := echo.New()

	// 定义静态文件目录
	e.Static("/", "static")

	// Logger(日志) 中间件
	e.Use(middleware.Logger())

	// Recover 中间件
	e.Use(middleware.Recover())

	// 登录权限拦截
	e.Use(before.InterceptLoginPermissions)

	// 注册模板
	t := &Template{
		templates: template.Must(template.ParseGlob("views/*.html")),
	}
	e.Renderer = t

	// 错误页面导向
	e.HTTPErrorHandler = customHTTPErrorHandler

	// 注册路由
	router.InitRouter(e)

	e.Server.Addr = fmt.Sprintf(":%v", port)

	// Start server
	e.Logger.Fatal(gracehttp.Serve(e.Server))
}
